const { Shopping } = require('../../schemas')

const addShopping = async (request, reply) => {
  const result = new Shopping(request.body)
  const data = await result.save()
  if (data) {
    return reply.code(200).send({
      code: reply.statusCode,
      message: '添加成功!',
      data: null,
      error: null,
    })
  } else {
    return reply.code(400).send({
      code: reply.statusCode,
      message: '添加失败！',
      data: null,
      error: '添加失败！',
    })
  }
}

const getShopping = async (request, reply) => {
  const result = await Shopping.find({}, { __v: 0, _id: 0 })
  if (result) {
    return reply.code(200).send({
      code: reply.statusCode,
      message: '成功',
      data: result,
      error: null,
    })
  } else {
    return reply.code(400).send({
      code: reply.statusCode,
      message: '添加失败！',
      data: null,
      error: '添加失败！',
    })
  }
}

const delShopping = async (request, reply) => {
  const { productId } = request.body
  const result = await Shopping.deleteOne({ productId: productId })
  if (result) {
    return reply.code(200).send({
      code: reply.statusCode,
      message: '删除成功！',
      data: null,
    })
  }
}
const putShopping = async (request, reply) => {
  const { productId } = request.body
  const update = await Shopping.findOneAndUpdate(
    { productId: productId },
    request.body,
    { new: true }
  )
  if (update) {
    return reply.code(200).send({
      code: reply.statusCode,
      message: '更新成功！',
      data: null,
    })
  } else {
    return reply.code(400).send({
      code: reply.statusCode,
      message: '更新失败！',
      data: null,
    })
  }
}

module.exports = {
  addShopping,
  getShopping,
  delShopping,
  putShopping,
}
